package com.zxd.threads.thread_correspondence;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:Shop
 * Package:com.zxd.threads.thread_correspondence
 *
 * @Date:2023/9/26 18:52
 * @Author:zxde
 */
public class Shop {
    private List<String> goods = new ArrayList<>();

    //生产者进程
    public synchronized void createGood() {
        try {
            if (goods.size() == 0){
                Thread.sleep(1000);
                goods.add(Thread.currentThread().getName() + "生产一个商品");
                System.out.println(Thread.currentThread().getName() + "生产一个商品");
                //唤醒其余进程，需要先唤醒，再睡眠
                this.notifyAll();
                //自己进入等待
                this.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void getGood() {
        try {
            if (goods.size() != 0){
                Thread.sleep(1000);
                goods.add(Thread.currentThread().getName() + "消耗商品");
                System.out.println(Thread.currentThread().getName() + "消耗一个商品");
                goods.clear();
                //唤醒其余进程
                this.notifyAll();
                //自己进入等待
                this.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
